package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/10 9:24
 * https://leetcode-cn.com/problems/reverse-words-in-a-string/
 */
public class Title151 {

    public static String reverseWords(String s) {
//        String[] split = s.trim().split(" ");
        StringBuilder builder = removeZero(s);
        StringBuilder result = new StringBuilder();
//        for (int i = split.length - 1; i >= 0; i--) {
//            if (!"".equals(split[i])) {
//                result.append(split[i]);
//                if (i != 0) {
//                    result.append(" ");
//                }
//            }
//        }
        return result.toString();
    }

    public static StringBuilder removeZero(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (s.charAt(left) == ' ') {
            left++;
        }
        while (s.charAt(right) == ' ') {
            right--;
        }
        StringBuilder result = new StringBuilder();
        while (left <= right) {
            if (s.charAt(left) != ' ' || result.charAt(result.length() - 1) != ' ') {
                result.append(s.charAt(left));
            }
            left++;
        }
        return result;
    }


    public String reverseWords1(String s) {
        String[] split = s.trim().split(" +");
        StringBuilder result = new StringBuilder();
        for (int i = split.length - 1; i >= 0; i--) {
            result.append(split[i]);
            if (i != 0) {
                result.append(" ");
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String s = "  hello s    world  ";
        reverseWords(s);

    }
}
